﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoader : MonoBehaviour
{
    public string nextSceneName = "";
    public bool isActivateOnComplete = false;

    public bool isAutoLoad = false;
    private AsyncOperation _asyncOperation;

    private void Awake()
    {
        if (GameObject.FindObjectsOfType<SceneLoader>().Length > 1)
        {
            Destroy(this);
        }
        else
        {
            DontDestroyOnLoad(this);
        }
    }

    private void Start()
    {
        if (isAutoLoad)
        {
            LoadNextSceneAsync(LoadSceneMode.Single);
        }
    }

    public void LoadNextSceneAsync(LoadSceneMode loadSceneMode)
    {
        if (nextSceneName == "")
        {
            Debug.LogError("没有指定需要加载的场景名字");
        }

        StartCoroutine(LoadSceneCoroutine(loadSceneMode));
    }
    
    public void LoadNextSceneAsync(string sceneName, LoadSceneMode loadSceneMode = LoadSceneMode.Single)
    {
        nextSceneName = sceneName;
        
        LoadNextSceneAsync(loadSceneMode);
    }
    
    public void LoadRouteScene(bool isAutoLoad = false, bool isActivateOnComplete = true, LoadSceneMode loadSceneMode = LoadSceneMode.Single)
    {
        nextSceneName = "2_Route";
        this.isAutoLoad = isAutoLoad;
        this.isActivateOnComplete = isActivateOnComplete;
        
        LoadNextSceneAsync(loadSceneMode);
    }

    IEnumerator LoadSceneCoroutine(LoadSceneMode loadSceneMode)
    {
        _asyncOperation = SceneManager.LoadSceneAsync(nextSceneName, loadSceneMode);
        
        // 允许自动跳转
        _asyncOperation.allowSceneActivation = isActivateOnComplete;

        while (!_asyncOperation.isDone)
        {
            if (isActivateOnComplete == false && _asyncOperation.progress >= .9f)
            {
                Debug.Log("请按任意键确认");
                if (Input.anyKeyDown)
                {
                    Debug.Log("已确认");
                    _asyncOperation.allowSceneActivation = true;
                }
            }

            yield return null;
        }

        ResetParams();
    }

    public void ResetParams()
    {
        nextSceneName = "";
        isActivateOnComplete = false;
        isAutoLoad = false;
    }
}
